package jus.aor.mobilagent.kernel;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AgentServer extends Thread{

	protected HashMap<String,_Service<?>> listeService=new HashMap<String,_Service<?>>();
	protected Server server;
	private int port;
	public AgentServer(Server server,int port){
		this.port=port;
		this.server = server;
	}
	
    

	@Override
	public void run() {
		ServerSocket ss;
		try {
			ss = new ServerSocket(port);
			while(true){
				Socket soc = ss.accept();
				InputStream ois = soc.getInputStream();
				
				AgentInputStream ais = new AgentInputStream(this.getClass().getClassLoader(),this,ois);
				
				Agent a = ais.readAgent();
				a.run();
			}

		} catch (IOException e) {
			e.printStackTrace();
			try {
				Logger logger=Logger.getLogger("jus/aor/mobilagent/"+InetAddress.getLocalHost().getHostName()+"/"+this.server.name);
				logger.log(Level.FINE,"AgentServer - run : ", e);
			} catch (UnknownHostException ex) {};
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			try {
				Logger logger=Logger.getLogger("jus/aor/mobilagent/"+InetAddress.getLocalHost().getHostName()+"/"+this.server.name);
				logger.log(Level.FINE,"AgentServer - run : ", e);
			} catch (UnknownHostException ex) {};		}		
	}



	public void addService(String name, _Service<?> s) {
		listeService.put(name, s);		
	}
	
	public _Service<?> getService(String name){
		return listeService.get(name);
	}
	
	public String getNameServer(){
		return server.name;
	}
}
